package com.friend.chat.chat

import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ImageSpan
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.friend.chat.R
import com.friend.chat.base.BaseActivity
import com.friend.chat.databinding.ActivityGroupChatBinding
import com.friend.chat.db.ChatDatabase
import com.friend.chat.db.dao.MessageDao
import com.friend.chat.db.entity.MessageEntity
import com.friend.chat.page.bean.GroupBean
import com.friend.chat.page.bean.UserBean
import com.friend.chat.utils.*
import com.friend.chat.websocket.ChatMessageBean
import com.friend.chat.websocket.WebSocketManager
import com.google.gson.Gson
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.runOnUiThread
import java.util.*

class GroupChatActivity : BaseActivity<ActivityGroupChatBinding,GroupChatViewModel>() {
    private lateinit var mUserBean: UserBean
    private lateinit var mGroupBean: GroupBean
    private lateinit var mAdapter: GroupChatAdapter
    private var mList = ArrayList<ChatMessageBean>()
    private var mUserId = ""
    private var mToUids = ArrayList<String>()
    private var mUserHeader = ""

    private lateinit var mMessageDao: MessageDao
    private var mEmoSelected = false
    private var mCount = 0

    companion object {
        fun open(activity: Activity, userBean: UserBean, groupBean: GroupBean) {
            val intent = Intent(activity, GroupChatActivity::class.java)
            intent.putExtra("groupBean", groupBean)
            intent.putExtra("userBean", userBean)

            activity.startActivity(intent)
        }
    }

    override fun yourViewModel(): GroupChatViewModel = GroupChatViewModel()

    override fun yourViewBing(): ActivityGroupChatBinding {
        return ActivityGroupChatBinding.inflate(layoutInflater)
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mCount = 0
        mUserBean = intent.getSerializableExtra("userBean") as UserBean
        mGroupBean = intent.getSerializableExtra("groupBean") as GroupBean
        mUserId = mUserBean.uid
        mUserHeader = mUserBean.header
        mToUids = mGroupBean.memberIds

        mMessageDao = ChatDatabase.getDatabase(this).messageDao()
        mViewBinding.tvTitle.text = mGroupBean.groupName
        initRecyclerView()
        //网络获取已读
        getDataBaseMessages()
        mVModel.getUnReadGroupChatList(mGroupBean.groupId,mUserId)
    }

    private fun initRecyclerView() {
        //聊天内容recycleView
        val linearLayoutManager = object : LinearLayoutManager(this) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        linearLayoutManager.stackFromEnd = true
        mAdapter = GroupChatAdapter(mList, mUserBean, mGroupBean)
        mViewBinding.rvChatGroup.layoutManager = linearLayoutManager
        mViewBinding.rvChatGroup.adapter = mAdapter
        mViewBinding.srlGroup.setOnRefreshListener {
            //  getDataBaseMessages()
        }


        val gridLayoutManager = object : GridLayoutManager(this, 8) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        val emojiAdapter =
            object : BaseQuickAdapter<EmojiBean, BaseViewHolder>(R.layout.item_emoji) {
                override fun convert(holder: BaseViewHolder, item: EmojiBean) {
                    holder.setImageResource(R.id.iv_emoji, item.emojiRes)
                }
            }

        mViewBinding.rvEmoji.layoutManager = gridLayoutManager
        mViewBinding.rvEmoji.adapter = emojiAdapter
        val emojiList = EmojiUtil.getEmojiList()
        emojiAdapter.setList(emojiList)
        emojiAdapter.setOnItemClickListener { adapter, _, position ->
            val data = adapter.data[position] as EmojiBean
            val spannableString = SpannableString(data.emojiString);
            val imageSpan = ImageSpan(this, BitmapFactory.decodeResource(resources,data.emojiRes))
            spannableString.setSpan(imageSpan,0,data.emojiString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            mViewBinding.edtTextMsg.append(spannableString)
        }

    }

    override fun onNetListener() {
        super.onNetListener()
        mVModel.unReadListResponse.observe(this){ result ->
            val data = result.data
            Thread{
                data?.apply {
                    val dataList = ArrayList<ChatMessageBean>()
                    //插入本地数据库
                    if (data.isNotEmpty()){
                        data.forEach {
                            try {
                                val messageEntity = MessageEntity()
                                messageEntity.userId = it.userId
                                messageEntity.toUid = it.toUid
                                messageEntity.type = it.type
                                messageEntity.roomType = it.type
                                messageEntity.message = it.message.toString()
                                messageEntity.dateTime = it.dateTime ?: "2022-12-24 18:15:00"
                                messageEntity.messageId = it.messageId ?: ""
                                messageEntity.roomId = it.roomId ?: ""
                                //下面的仅群聊有
                                messageEntity.fromNickname = it.fromNickname
                                messageEntity.fromHeader = it.fromHeader
                                mMessageDao.insertMessage(messageEntity)
                            } catch (e: Exception) {
                                //insert不进去
                            }
                        }
                    }
                    //从本地数据库取出来
                    val saveListData = mMessageDao.queryMessage(mGroupBean.groupId, 0)
                    if (saveListData.isNotEmpty()) {
                        saveListData.reverse()

                        for (data in saveListData) {
                            Log.e("--->", data.toString())
                            dataList.add(
                                ChatMessageBean(
                                    data.userId,
                                    data.toUid,
                                    data.type,
                                    data.roomType,
                                    data.message,
                                    data.dateTime,
                                    data.messageId,
                                    mGroupBean.groupId,
                                    fromNickname = data.fromNickname,
                                   fromHeader = data.fromHeader,
                                )
                            )
                        }
                    }
                    runOnUiThread {
                        mAdapter.setList(dataList)
                        if (mAdapter.data.size > 0) {
                            mViewBinding.rvChatGroup.smoothScrollToPosition(mAdapter.data.size - 1)
                        }
                        sendReadAck()
                    }
                }
            }.start()
        }
    }

    private fun getDataBaseMessages() {
        Thread {
            val dataList = ArrayList<ChatMessageBean>()
            dataList.clear()
            //从本地数据库取出来
            mCount = (mCount+1)*20
            val saveListData =
                mMessageDao.queryMessage(mGroupBean.groupId, 0)
            if (saveListData.isNotEmpty()) {
                saveListData.reverse()
                for (data in saveListData) {
                    Log.e("--->", data.toString())
                    dataList.add(
                        ChatMessageBean(
                            data.userId,
                            data.toUid,
                            data.type,
                            data.roomType,
                            data.message,
                            data.dateTime,
                            data.messageId,
                            mGroupBean.groupId,
                            fromNickname = data.fromNickname,
                            fromHeader = data.fromHeader,
                        )
                    )
                }
            }
            runOnUiThread {
                mViewBinding.srlGroup.finishRefresh()
                Log.e("-->","dataList.size==>"+dataList.size)
                Log.e("--->","mCount==>"+mCount)
                if (dataList.size > 0) {
                    mAdapter.addData(0,dataList)
                    //  mViewBinding.rvChatSingle.smoothScrollToPosition(mAdapter.data.size - 1)
                }else{
                    mViewBinding.srlGroup.setEnableRefresh(false)
                }

            }

        }.start()
    }

    override fun setClick() {
        super.setClick()

        mViewBinding.ivHeaderSetting.setOnClickListener {


        }

        mViewBinding.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.btnSetModeVoice.setOnClickListener {
            //   AudioActivity.open(this, mGroupBean.friendId, true)
        }

        mViewBinding.ivEmojiNormal.setOnClickListener {
            mEmoSelected = !mEmoSelected
            mViewBinding.ivEmojiNormal.isSelected = mEmoSelected

            if (mEmoSelected){
                hideKeyboard(this)
                mViewBinding.rvEmoji.visibility = View.VISIBLE

            }else{
                mViewBinding.rvEmoji.visibility = View.GONE
                showKeyboard(this,mViewBinding.edtTextMsg)
            }
        }

        mViewBinding.btnSend.setOnClickListener {
            val text = mViewBinding.edtTextMsg.text.toString()
            val messId = UUID.randomUUID().toString()
            val dateTime = DateUtils.getTodayDate()
            val message = ChatMessageBean(
                mUserId,
                "-1",
                type = CHAT_TEXT,
                roomType = CHAT_ROOM_GROUP,
                message = text,
                dateTime,
                messId,
                mGroupBean.groupId,
                fromNickname = mUserBean.nickname,
                fromHeader = mUserBean.header
            )
            mToUids.forEach {
                //不要发给自己
                if (it != mUserId) {
                    message.toUid = it
                    //发送
                    WebSocketManager.instance.sendMessage(Gson().toJson(message))
                }
            }
            mAdapter.addData(message)
            mViewBinding.rvChatGroup.smoothScrollToPosition(mAdapter.data.size - 1)
            mViewBinding.edtTextMsg.setText("")
            //数据库操作
            Thread {
                try {
                    val messageEntity = MessageEntity()
                    messageEntity.userId = mUserId
                    messageEntity.toUid = "-1"
                    messageEntity.type = CHAT_TEXT
                    messageEntity.roomType = CHAT_ROOM_GROUP
                    messageEntity.message = text
                    messageEntity.dateTime = dateTime
                    messageEntity.messageId = messId
                    messageEntity.roomId = mGroupBean.groupId
                    messageEntity.fromNickname = mUserBean.nickname
                    messageEntity.fromHeader = mUserBean.header
                    mMessageDao.insertMessage(messageEntity)
                } catch (e: Exception) {
                    Log.e("---->", e.message ?: "")
                }
            }.start()

        }

        mViewBinding.edtTextMsg.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (hasFocus) {
                    mEmoSelected = false
                    mViewBinding.ivEmojiNormal.isSelected = mEmoSelected
                    mViewBinding.rvEmoji.visibility = View.GONE
                }
            }


        mViewBinding.edtTextMsg.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s!=null&& s.isNotEmpty()){
                    mViewBinding.btnSend.visibility = View.VISIBLE
                    mViewBinding.btnMore.visibility = View.GONE
                }else{
                    mViewBinding.btnSend.visibility = View.GONE
                    mViewBinding.btnMore.visibility = View.VISIBLE
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
    }

    class GroupChatAdapter : BaseMultiItemQuickAdapter<ChatMessageBean, BaseViewHolder> {
        private var mUserBean: UserBean
        private var mGroupBean: GroupBean

        constructor(
            data: MutableList<ChatMessageBean>?,
            userBean: UserBean,
            groupBean: GroupBean
        ) : super(data) {
            addItemType(1, R.layout.item_chat_text)
            mUserBean = userBean
            mGroupBean = groupBean
        }

        override fun convert(holder: BaseViewHolder, item: ChatMessageBean) {
            when (holder.itemViewType) {
                //text
                1 -> {
                    val dateTimeView = holder.getView<TextView>(R.id.tv_item_datetime)
                    val leftView = holder.getView<LinearLayout>(R.id.ll_item_text_left)
                    val rightView = holder.getView<LinearLayout>(R.id.ll_item_text_right)
                    val friendHeaderView = holder.getView<ImageView>(R.id.iv_item_text_friend)
                    val meHeaderView = holder.getView<ImageView>(R.id.iv_item_text_me)
                    val fromNickname =holder.getView<TextView>(R.id.tv_item_text_friend_nickname)
                    fromNickname.visibility = View.VISIBLE
                    dateTimeView.text = item.dateTime
                    if (mUserBean.uid != item.userId) {
                        //左边的 -- friend
                        leftView.visibility = View.VISIBLE
                        rightView.visibility = View.GONE
                        Thread{
                            val str = EmojiUtil.getEmojisText(context,item.message.toString())
                            context.runOnUiThread {
                                holder.setText(R.id.tv_item_text_friend,
                                    EmojiUtil.getEmojisText(context,item.message.toString()) )
                            }
                        }.start()
                        fromNickname.text = item.fromNickname

                         GlideUtils.loadRadiusImg1(friendHeaderView, item.fromHeader, 4)
                    } else {
                        //右边的 -- me
                        rightView.visibility = View.VISIBLE
                        leftView.visibility = View.GONE
                        //   holder.setText(R.id.tv_item_text_me,EmojiUtil.getEmojisText(context,item.message.toString()))
                        GlideUtils.loadRadiusImg1(meHeaderView, mUserBean.header, 4)
                        Thread{
                            val str = EmojiUtil.getEmojisText(context,item.message.toString())
                            context.runOnUiThread {
                                holder.setText(R.id.tv_item_text_me,
                                    EmojiUtil.getEmojisText(context,item.message.toString()) )
                            }

                        }.start()

                    }
                }
                else -> {}
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: ChatMessageBean?) {
        event?.apply {
            //roomType 0-单聊 1-群聊  2-公众号
            if (event.type != 0 && event.type != 5 && event.roomType == 1) {
                mAdapter.addData(event)
                mViewBinding.rvChatGroup.scrollToPosition(mAdapter.data.size - 1)
                Thread {
                    val messageEntity = MessageEntity()
                    messageEntity.userId = event.userId
                    messageEntity.toUid = event.toUid
                    messageEntity.type = event.type
                    messageEntity.roomType = event.roomType
                    messageEntity.message = event.message.toString()
                    messageEntity.dateTime = event.dateTime ?: ""
                    messageEntity.messageId = messageId ?: ""
                    messageEntity.roomId = event.roomId.toString()
                    messageEntity.fromNickname = event.fromNickname
                    messageEntity.fromHeader = event.fromHeader
                    mMessageDao.insertMessage(messageEntity)
                }.start()

                sendReadAck()
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    private fun sendReadAck() {
        //发送已读ack
           WebSocketManager.instance.sendMessage(
               Gson().toJson(
                   ChatMessageBean(
                       mUserId, toUid = "0",
                       type = CHAT_SYSTEM,
                       roomType = CHAT_ROOM_GROUP,
                       CHAT_READ_ACK,
                       roomId = mGroupBean.groupId
                   )
               )
           )
    }
}